import path from 'path';

import legacy from '@vitejs/plugin-legacy';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, loadEnv } from 'vite';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import { VitePWA } from 'vite-plugin-pwa';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import tsconfigPaths from 'vite-tsconfig-paths';

const env = loadEnv('development', './');
// console.log(process.env.NODE_ENV, env);

// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  esbuild: {
    // drop: ['console', 'debugger'],
  },
  css: {
    // 开css sourcemap方便找css
    devSourcemap: true,
  },
  plugins: [
    react(),
    legacy({
      targets: ['defaults', 'not IE 11'],
    }),
    // 同步tsconfig.json的path设置alias
    visualizer({
      // 可选配置项
      // open: true, // 是否自动打开生成的报告页面
      gzipSize: true, // 显示gzip后的大小
      brotliSize: true, // 显示brotli压缩后的大小
      // 更多配置选项...
    }),
    tsconfigPaths(),
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
      svgoOptions: true,
    }),
    nodePolyfills(),
    VitePWA({
      registerType: 'autoUpdate', // 自动注册和更新
      manifest: {
        name: 'EAI',
        short_name: 'EAI',
        theme_color: '#eceff7',
        background_color: '#eceff7',
      },
      workbox: {
        maximumFileSizeToCacheInBytes: 50 * 1024 * 1024,
        globPatterns: ['**/*.{js,css,ico,png,svg}'],
        skipWaiting: true, // 跳过等待阶段
        clientsClaim: true, // 立即接管控制
      },
      devOptions: {
        enabled: false, // 开发环境也启用
      },
    }),
  ],
  resolve: {
    alias: {
      crypto: 'node-libs-browser/mock/crypto',
      eaid: path.resolve(__dirname, 'src/components/eai-design'),
    },
  },
  server: {
    // 自动打开浏览器
    open: true,
    host: true,
    port: 3001,
    proxy: {
      '/api/ts/v1': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace('/api/ts/v1', '/api/ts/v1');
        },
      },
      '/api/metahuman': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace('/api/metahuman', '/api/metahuman');
        },
      },
      '/imgs': {
        target: env.VITE_GATEWAY_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace('/imgs', '/api/imgs');
        },
      },
      '/image': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/video': {
        target: env.VITE_VIDEOS_PREVEIS_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/openapi': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/api/webcrawl/openapi/v1': {
        target: env.VITE_WEBCRAWL_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/api/api_know': {
        target: env.VITE_CONNECTOR_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path.replace('/api/api_know', '');
        },
      },
      '/api/fcs/openapi/v1': {
        target: env.VITE_FCS_URL,
        changeOrigin: true,
        rewrite: (path) => {
          // return path.replace('/api/fcs', '/fcs');
          return path;
        },
      },
      '/api/agent/api': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/api/openapi/proxy': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
          // console.log(path.replace(/^\/api\/openapi\/proxy\/?.*/, ''), path);
          // const result = path.match(/\/[^\/]+$/) ?? '/offer';
          // return path.replace(/^\/api\/openapi\/proxy\/?.*/, result[0]);
        },
      },
      '/api/openapi': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        // configure: (proxy, _options) => {
        //   proxy.on('proxyReq', (proxyReq, req, _res) => {
        //     if (req.url?.includes('proxy')) {
        //       const path = req.url.replace('/openapi/proxy/', '');
        //       _options.target = 'http://' + path;
        //     } else {
        //       _options.target = env.VITE_BACKEND_URL;
        //     }
        //   });
        // },
        rewrite: (path) => {
          return path.replace(/^\/api\/openapi/, '/openapi');
        },
      },
      '/api/api/ruigpt': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          if (path.includes('/api/api')) {
            return path.replace('/api/api', '/api');
          }
          if (path.includes('/api/openapi/proxy')) {
            return path.replace('/api/openapi/proxy', '/');
          }
          if (path.includes('/api/openapi/')) {
            return path.replace('/api/openapi/', '/openapi');
          }
          return path;
        },
      },
      '/api/ruigpt': {
        target: env.VITE_BACKEND_URL,
        changeOrigin: true,
        rewrite: (path) => {
          if (path.includes('/api/api')) {
            return path.replace('/api/api', '/api');
          }
          if (path.includes('/api/openapi/proxy')) {
            return path.replace('/api/openapi/proxy', '/');
          }
          if (path.includes('/api/openapi/')) {
            return path.replace('/api/openapi/', '/openapi');
          }
          return path;
        },
      },
      '/api': {
        target: env.VITE_GPT_URL,
        changeOrigin: true,
        rewrite: (path) => {
          if (path.includes('/api/api')) {
            return path.replace('/api/api', '/api');
          }
          if (path.includes('/api/openapi/proxy')) {
            return path.replace('/api/openapi/proxy', '/');
          }
          if (path.includes('/api/openapi/')) {
            return path.replace('/api/openapi/', '/openapi');
          }
          return path;
        },
      },
      '/preview': {
        target: env.VITE_ONLINEPREVIEW_URL,
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      '/ws': {
        // 自定义一个路径，用于匹配 WebSocket 请求
        target: env.VITE_WEBSOCKET,
        ws: true, // 开启 WebSocket 代理
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/ws/, ''), // 可根据需要重写路径
      },
      // '/download': {
      //   target: 'http://10.110.163.177:12233/',
      //   changeOrigin: true,
      //   rewrite: (path) => {
      //     return path;
      //   },
      // },
      '/offer': {
        target: 'http://172.30.232.141:30031/',
        // target: 'http://10.110.163.199:30031/',
        changeOrigin: true,
        rewrite: (path) => {
          return path;
        },
      },
      // '/human': {
      //   target: 'http://172.30.232.141:30031/',
      //   // target: 'http://10.110.163.199:30031/',
      //   changeOrigin: true,
      //   rewrite: (path) => {
      //     return path;
      //   },
      // },
    },
  },
  assetsInclude: ['**/*.worker.min.js'],
  build: {
    target: 'es2015',
    minify: 'terser',
    chunkSizeWarningLimit: 1000,
    rollupOptions: {
      output: {
        manualChunks: {
          // lodash: ['lodash'],
          // echarts: ['echarts'],
          react: ['react', 'react-dom'],
          antd: ['antd', '@ant-design/icons'],
          echarts: ['echarts', 'echarts-wordcloud', 'echarts-for-react'],
          editor: ['lexical', 'react-quill', '@monaco-editor/react'],
          i18n: ['i18next', 'react-i18next'],
          socket: ['socket.io-client'],
          pdfjs: ['pdfjs-dist'],
        },
      },
    },
    terserOptions: {
      compress: {
        // 生产环境移除console
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
});
